package io.renren.modules.task.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.renren.common.exception.RRException;
import io.renren.modules.project.mapper.ProjectMapper;
import io.renren.modules.project.model.ProjectDo;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.task.mapper.TaskDetailMapper;
import io.renren.modules.task.mapper.TaskMapper;
import io.renren.modules.task.mapper.UserTaskMapper;
import io.renren.modules.task.model.*;
import io.renren.modules.task.service.TaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service("taskService")
public class TaskServiceImpl extends AbstractController implements TaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private TaskDetailMapper taskDetailMapper;

    @Autowired
    private UserTaskMapper userTaskMapper;

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private ProjectMapper projectMapper;

    public List<TaskVo> getUserRealName(List<TaskVo> taskList) {
        List<TaskVo> taskVos = new ArrayList<>();
        Map<Long, SysUserEntity> userNameListMap = sysUserDao.getUserNameListMap();
        for (TaskVo taskVo : taskList) {
            String[] arrStrAllocateUserIds = taskVo.getAllocateUserIds().split(",");
            StringBuffer sb = new StringBuffer();
            for (String arrStrAllocateUserId : arrStrAllocateUserIds) {
                long l = Long.parseLong(arrStrAllocateUserId);
                if (userNameListMap.containsKey(l)) {
                    SysUserEntity sysUserEntity = userNameListMap.get(l);
                    if (sb.toString().length() > 0) {
                        sb.append("," + sysUserEntity.getRealName());
                    } else {
                        sb.append(sysUserEntity.getRealName());
                    }
                }
            }
            taskVo.setAllocateUserNames(sb.toString());
            Long headUerId = taskVo.getHeadUerId();
            if (userNameListMap.containsKey(headUerId)) {
                taskVo.setHeadUserName(userNameListMap.get(headUerId).getRealName());
            }
            Long auditUserId = taskVo.getAuditUserId();
            if (userNameListMap.containsKey(auditUserId)) {
                taskVo.setAuditUserName(userNameListMap.get(auditUserId).getRealName());
            }
            taskVos.add(taskVo);
        }
        return taskVos;
    }

    @Override
    public PageInfo<TaskVo> createTaskList(Integer pageNum, Integer pageSize) {
        Long createUserId = Long.valueOf(String.valueOf(getUserId()));
        PageHelper.startPage(pageNum, pageSize);
        List<TaskVo> taskList = taskMapper.createTaskList(createUserId);
        if (taskList.size() > 0) {
            taskList = getUserRealName(taskList);
        }
        PageInfo<TaskVo> taskVoPageInfo = new PageInfo<>(taskList);
        return taskVoPageInfo;
    }

    /**
     * 任务列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<TaskVo> queryPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<TaskVo> taskList = taskMapper.getTaskList();
        if (taskList.size() > 0) {
            taskList = getUserRealName(taskList);
        }
        PageInfo<TaskVo> taskVoPageInfo = new PageInfo<>(taskList);
        return taskVoPageInfo;
    }

    /**
     * 我的任务列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<TaskVo> myTaskList(Integer pageNum, Integer pageSize) {
        Long userId = Long.valueOf(String.valueOf(getUserId()));
        PageHelper.startPage(pageNum, pageSize);
        List<TaskVo> taskList = taskMapper.myTaskList(userId);
        if (taskList.size() > 0) {
            taskList = getUserRealName(taskList);
        }
        PageInfo<TaskVo> taskVoPageInfo = new PageInfo<>(taskList);
        return taskVoPageInfo;
    }

    /**
     * 审核任务列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<TaskVo> auditTaskList(Integer pageNum, Integer pageSize) {
        Long auditUserId = Long.valueOf(String.valueOf(getUserId()));
        PageHelper.startPage(pageNum, pageSize);
        List<TaskVo> taskList = taskMapper.auditTaskList(auditUserId);
        PageInfo<TaskVo> taskVoPageInfo = new PageInfo<>(taskList);
        return taskVoPageInfo;
    }

    @Override
    public TaskDetail getTaskDetail(Long taskId) {
        TaskDetail taskDetail = taskMapper.getTaskDetail(taskId);
        return taskDetail;
    }

    @Override
    public TaskVo getById(Long id) {
        TaskVo taskVo = taskMapper.getById(id);
        return taskVo;
    }

    @Override
    @Transactional
    public Integer save(TaskBo taskBo) {
        Integer userId = Integer.valueOf(String.valueOf(getUserId()));
        TaskDo taskDo = new TaskDo();
        BeanUtils.copyProperties(taskBo, taskDo);
        //1.创建任务
        taskDo.setCreateUserId(userId);
        Integer update = taskMapper.save(taskDo);
        if (update > 0) {
            //2.创建一条任务明细
            TaskDetailDo taskDetailDo = new TaskDetailDo();
            taskDetailDo.setTaskId(taskDo.getTaskId());
            taskDetailDo.setCreateTime(new Date());
            taskDetailDo.setOperationUserId(taskBo.getCreateUserId());
            taskDetailDo.setTaskRecord("创建任务");
            taskDetailDo.setOperationUserId(userId);
            taskDetailMapper.insert(taskDetailDo);

            //3.创建任务分配人和任务之间关联表信息
            String[] allocateUserIdArray = taskBo.getAllocateUserIds().split(",");
            List<String> s = Arrays.asList(allocateUserIdArray.clone());
            boolean contains = s.contains(taskBo.getHeadUerId().toString());
            if (!contains) {
                throw new RRException("负责人必须是分配人中的一个");
            }
            for (String allocateUserId : allocateUserIdArray) {
                Integer isHead = 0;
                Long allocateUserIdLong = Long.parseLong(allocateUserId);
                if (allocateUserIdLong.equals(taskBo.getHeadUerId())) {
                    isHead = 1;
                }
                UserTaskDo userTaskDo = new UserTaskDo();
                userTaskDo.setCreateTime(new Date());
                userTaskDo.setIsHead(isHead);
                userTaskDo.setTaskId(taskDo.getTaskId());
                userTaskDo.setUserId(allocateUserIdLong);
                userTaskMapper.insert(userTaskDo);
            }
            //修改项目状态为进行中
            ProjectDo projectDo = new ProjectDo();
            projectDo.setProjectId(taskBo.getProjectId());
            projectDo.setProjectStatus(1);
            projectMapper.updateById(projectDo);
        }
        return update;
    }

    @Override
    public Integer update(TaskBo taskBo) {
        TaskDo taskDo = new TaskDo();
        BeanUtils.copyProperties(taskBo, taskDo);
        return taskMapper.update(taskDo);
    }

    @Override
    public Integer delete(Long[] ids) {

        return taskMapper.deleteIds(ids);
    }

}